package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.CommunityBrokerage;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.request.UserCommunityBindFrontReq;
import com.zbkj.common.response.UserCommunityFrontInfoResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.UserCommunity;
import com.zbkj.service.dao.UserCommunityDao;
import com.zbkj.service.service.CommunityBrokerageService;
import com.zbkj.service.service.UserCommunityService;

import com.zbkj.common.request.UserCommunitySaveRequest;
import com.zbkj.common.request.UserCommunitySearchRequest;
import com.zbkj.common.response.UserCommunityPageDataResponse;
import com.zbkj.common.response.UserCommunityDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Caiyc
* @description UserCommunityServiceImpl 接口实现
* @date 2025-07-28
*/
@Service
public class UserCommunityServiceImpl extends ServiceImpl<UserCommunityDao, UserCommunity> implements UserCommunityService {

    @Resource
    private UserCommunityDao dao;
    @Autowired
    private UserService userService;
    @Autowired
    private CommunityBrokerageService communityBrokerageService;

    @Override
    public Boolean create(UserCommunitySaveRequest userCommunitySaveRequest) {
        UserCommunity userCommunity = new UserCommunity();
        BeanUtils.copyProperties(userCommunitySaveRequest, userCommunity, "id");
        boolean save = save(userCommunity);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询用户小区绑定表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<UserCommunity>
     * @author Caiyc
     * @since 2025-07-28
     */
    @Override
    public List<UserCommunityPageDataResponse> getList(UserCommunitySearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<UserCommunity> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.orderByDesc(UserCommunity::getCreateTime);
        List<UserCommunity> userCommunitys = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<UserCommunityPageDataResponse> userCommunityResponses = new ArrayList<>();

        userCommunitys.stream().forEach(x->{
            UserCommunityPageDataResponse userCommunityResponse = new UserCommunityPageDataResponse();
            BeanUtils.copyProperties(x, userCommunityResponse);
            userCommunityResponses.add(userCommunityResponse);
        });
        return userCommunityResponses;
    }

    /**
    * 修改用户小区绑定表
    * @param request
    * @return
    */
    @Override
    public boolean update(UserCommunitySaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入用户小区绑定表ID");
        }
        getByIdException(request.getId());
        UserCommunity userCommunity = new UserCommunity();
        BeanUtils.copyProperties(request, userCommunity);
        return updateById(userCommunity);
    }

    private UserCommunity getByIdException(Integer id) {
        UserCommunity userCommunity = getById(id);
        if (ObjectUtil.isNull(userCommunity)) {
            throw new AppException("用户小区绑定表不存在");
        }
        if (userCommunity.getIsDel()) {
            throw new AppException("用户小区绑定表不存在");
        }
        return userCommunity;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<UserCommunity> luw = Wrappers.lambdaUpdate();
        luw.set(UserCommunity::getIsDel, true);
        luw.in(UserCommunity::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除用户小区绑定表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public UserCommunityDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<UserCommunity> lqw = Wrappers.lambdaQuery();
        lqw.eq(UserCommunity::getIsDel, 0);
        lqw.last("limit 1");
        UserCommunity userCommunity = this.getOne(lqw);
        if (ObjectUtil.isNotNull(userCommunity)) {
            UserCommunityDetailResponse response = new UserCommunityDetailResponse();
            BeanUtils.copyProperties(userCommunity, response);
            return response;
        }
        return null;
    }

    @Override
    public UserCommunity getByUid(Integer uid) {
        LambdaQueryWrapper<UserCommunity> lqw = Wrappers.lambdaQuery();
        lqw.eq(UserCommunity::getIsDel, 0);
        lqw.eq(UserCommunity::getIsUnbind, 0);
        lqw.eq(UserCommunity::getUid, uid);
        lqw.orderByDesc(UserCommunity::getBindTime);
        lqw.last("limit 1");
        return this.getOne(lqw);
    }

    /**
     * 我的小区信息
     * @return
     */
    @Override
    public UserCommunityFrontInfoResponse getUserCommunityInfo() {
        User user = userService.getInfo();
        UserCommunity userCommunity = getByUid(user.getId());
        if (userCommunity != null) {
            UserCommunityFrontInfoResponse response = new UserCommunityFrontInfoResponse();
            BeanUtils.copyProperties(userCommunity, response);
            return response;
        }
        return null;
    }

    /**
     * 绑定小区
     * @param bindProductRequest
     * @return
     */
    @Override
    public Boolean bindCommunity(UserCommunityBindFrontReq bindProductRequest) {
        User user = userService.getInfo();
        UserCommunity userCommunity = getByUid(user.getId());
        if (userCommunity != null) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "您已绑定过小区，请先解绑再进行绑定");
        }
        UserCommunity userCommunityUpdate = new UserCommunity();
        userCommunityUpdate.setCommunityId(bindProductRequest.getCommunityId());
        userCommunityUpdate.setUid(user.getId());
        userCommunityUpdate.setBindTime(new Date());

        LambdaQueryWrapper<CommunityBrokerage> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.select(CommunityBrokerage::getCommunity);
        checkWrapper.eq(CommunityBrokerage::getIsDel, 0);
        checkWrapper.eq(CommunityBrokerage::getMerId, 0);
        checkWrapper.eq(CommunityBrokerage::getId, bindProductRequest.getCommunityId());
        CommunityBrokerage communityBrokerage = communityBrokerageService.getOne(checkWrapper);
        if (ObjectUtil.isNotNull(communityBrokerage)) {
            userCommunityUpdate.setCommunity(communityBrokerage.getCommunity());
            userCommunityUpdate.setLongitude(communityBrokerage.getLongitude());
            userCommunityUpdate.setLatitude(communityBrokerage.getLatitude());
        }
        this.save(userCommunityUpdate);
        return true;
    }

    /**
     * 解绑小区
     * @return
     */
    @Override
    public Boolean unbindCommunity() {
        User user = userService.getInfo();
        UserCommunity userCommunity = getByUid(user.getId());
        if (userCommunity == null) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "您还未绑定小区");
        }
        userCommunity.setIsUnbind(true);
        userCommunity.setUnbindTime(new Date());
        userCommunity.setUpdateTime(new Date());
        this.updateById(userCommunity);
        return true;
    }

}

